package com.ying.dogying.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ying.dogying.entity.*;
import com.ying.dogying.entity.dto.ImUserMessageDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/im-userInfo")
public class ImUserInfoController extends BaseController{

    /**
     * 1.-----------------------------------我的主页-----------------------------------
     */
    @GetMapping("/home")
    public String home() {
        ImUser imUser = new ImUser();
        String authorId = request.getParameter("authorId");
        imUser = imUserService.getById(StringUtils.isBlank(authorId) ? getProfileId() : authorId);
        imUser.setPassword(null);
        // 查询30天内容的文章
        List<ImPost> postList = imPostService.selectBy30Before(getProfileId());
        request.setAttribute("imUser", imUser);
        request.setAttribute("postList", postList);
        return "userInfo/home";
    }

    /**
     * 查询我发表的文章
     */
    @GetMapping("/myPublishedPost")
    public String myPublishedPost() {
        IPage<ImPost> myPublishedPost = imPostService.selectByUserId(getPage(), getProfileId());
        request.setAttribute("myPublishedPost", myPublishedPost);
        return "userInfo/center";
    }

    /**
     * 查询我收藏的文章
     */
    @GetMapping("/myCollectionPost")
    public String myCollectionPost() {
        IPage<ImUserCollection> myCollectionPost = imUserCollectionService.selectByUserId(getPage(), getProfileId());
        request.setAttribute("myCollectionPost", myCollectionPost);
        return "userInfo/center";
    }

    /**
     * 查询是否是我收藏的文章
     */
    @PostMapping("/myCollectionPost/find")
    public @ResponseBody Response whetherI(Long postId) {
        int count = imUserCollectionService.count(new QueryWrapper<ImUserCollection>()
                .eq("user_id", getProfileId())
                .eq("post_id", postId)
        );
        return new Response().success(MapUtil.of("collection", count > 0 ));
    }

    /**
     * 收藏文章
     */
    @PostMapping("/myCollectionPost/add")
    public @ResponseBody Response add(Long postId) {
        ImPost post = imPostService.getById(postId);
        Assert.isTrue(post != null, "该帖子已被删除");
        int count = imUserCollectionService.count(new QueryWrapper<ImUserCollection>()
                .eq("post_id", postId)
                .eq("user_id", getProfileId()));
        if(count > 0) {
            return new Response().failure("你已经收藏");
        }
        ImUserCollection collection = new ImUserCollection();
        collection.setUserId(getProfileId());
        collection.setCreateTime(new Date());
        collection.setUpdateTime(new Date());
        collection.setPostId(post.getId());
        collection.setPostUserId(post.getUserId());
        imUserCollectionService.save(collection);
        return  new Response().success(MapUtil.of("collection", true));
    }

    /**
     * 取消收藏
     */
    @PostMapping("/myCollectionPost/del")
    public @ResponseBody Response del(Long postId) {
        ImPost post = imPostService.getById(Long.valueOf(postId));
        Assert.isTrue(post != null, "该帖子已被删除");
        boolean hasRemove = imUserCollectionService.remove(new QueryWrapper<ImUserCollection>()
                .eq("post_id", postId)
                .eq("user_id", getProfileId()));
        return new Response().success(hasRemove);
    }

    /**
     * 2.-----------------------------------用户中心-----------------------------------
     */
    @GetMapping("/center")
    public String center() {
        return "userInfo/center";
    }

    /**
     * 3.-----------------------------------基本设置-----------------------------------
     */
    @GetMapping("/basicSetup")
    public String basicSetup() {
        ImUser imUser = imUserService.getById(getProfileId());
        imUser.setPassword(null);
        request.setAttribute("imUser", imUser);
        return "userInfo/setup";
    }

    /**
     * 编辑基本设置
     * @throws IOException 
     */
    @PostMapping("/basicSetup/edit")
    public Response editBasicSetup(ImUser imUser) {
    	Response updateByParams = imUserService.updateByParams(imUser, getProfileId(), getProfile());
    	if("-1".equals(updateByParams.getCode())) {
    		return updateByParams;
    	}else {
    		return updateByParams.action("/userInfo/set");
    	}
    }

    @PostMapping("/upload")
    public Response upload(@RequestParam(value = "file") MultipartFile file,
                           @RequestParam(name = "type", defaultValue = "avatar") String type) {
        Response response = imUserService.upload(file, type, getProfileId(), getProfile());
        return response;
    }

    @PostMapping("/rePassword")
    public Response rePassword(String nowPassword, String password, String rePassword) throws IOException {
        if(!password.equals(rePassword)) {
            return new Response().failure("两次密码不相同");
        }
        ImUser imUser = imUserService.getById(getProfileId());

        String nowPassMd5 = SecureUtil.md5(nowPassword);
        if(!nowPassMd5.equals(imUser.getPassword())) {
            return new Response().failure("密码不正确");
        }

        imUser.setPassword(SecureUtil.md5(password));
        imUserService.updateById(imUser);

        return new Response().success("更新成功").action("/im-userInfo/center");
    }

    /**
     * 4.-----------------------------------我的消息-----------------------------------
     */
    @GetMapping("/message")
    public String message() {

        IPage<ImUserMessageDto> pageData = imUserMessageService.selectByParams(getPage(), getProfileId());

        request.setAttribute("pageData", pageData);
        return "userInfo/message";
    }

    /**
     * 清除消息
     * @throws IOException 
     */
    @GetMapping("/delMessage")
    public Response delMessage(Long id, boolean b) {
        boolean remove = imUserMessageService.remove(new QueryWrapper<ImUserMessage>()
                .eq("to_user_id", getProfileId())
                .eq(!b, "id", id));
        return remove ? new Response().success("删除成功").action("userInfo/center") : new Response().failure("删除失败");
    }

}
